package edu.ntu.im.p2ptrade;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

import edu.ntu.im.p2ptrade.entity.User;
import edu.ntu.im.p2ptrade.security.KeyManager;

public class OwnerManager {
	
	private static User owner;
	private static String configHome;
	private static String ownerFile = "owner.obj";
	private static Boolean established = false;
	public static void initOwner (String config) throws Exception{
		configHome = config;
		File f = new File(configHome, ownerFile);
		if (f.exists()){
			FileInputStream fis;
			try {
				fis = new FileInputStream(f);
				ObjectInputStream ois = new ObjectInputStream(fis);
				owner = (User) ois.readObject();
				established = true;
			} catch (FileNotFoundException e) {
				e.printStackTrace();
				established = false;
			} catch (IOException e) {
				e.printStackTrace();
				established = false;
				owner = null;
			} catch (ClassNotFoundException e) {
				e.printStackTrace();
				established = false;
				owner = null;
			}
		}
		
		KeyManager.initialize();
		if (owner!= null){
			owner.setPublicKey(KeyManager.readCertification(KeyManager.PUBLIC_KEY_FILE)[0]);
		}
	}
	
	public static Boolean established(){
		return established;
	}
	
	public static void saveOwner(User user) throws Exception{
		owner = user;
		KeyManager.initialize();
		
		if (owner!= null){
			owner.setPublicKey(KeyManager.readCertification(KeyManager.PUBLIC_KEY_FILE)[0]);
		}
		
		File f = new File(configHome, ownerFile);
		if (!f.exists()){
				f.createNewFile();
		}
		
		FileOutputStream fos = new FileOutputStream(f);
		ObjectOutputStream oos = new ObjectOutputStream(fos);
		oos.writeObject(user);
		oos.close();
		
		
	}
	
	public static User getOwner(){
		return owner;
	}

}
